<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
      <span class="cat_goods">选择商品分类:</span>
      <div class="selection">
        <el-cascader v-model="value" :options="allgoods" :props="goodsprops" @change="handleChange"></el-cascader>
      </div>
      <!-- 渲染tab页签 -->
      <template>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" :disabled="isDisabled" @click="addparams">添加参数</el-button>
            <el-table border stripe :data="manyTabData">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleclose(scope.row,i)"
                  >{{item}}</el-tag>
                  <!--  -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 展开列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template size="mini" slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="editParams(scope.row.attr_id)"
                  >修改</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" :disabled="isDisabled" @click="addparams">添加参数</el-button>
            <el-table border stripe :data="onlyTabData">
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleclose(scope.row,i)"
                  >{{item}}</el-tag>
                  <!--  -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 展开列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template size="mini" slot-scope="scope">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="editParams(scope.row.attr_id)"
                  >修改</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form :model="addForm" ref="addFormRef" label-width="100px" :rules="addFormRules">
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="100px" :rules="editFormRules">
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeName: "many",
      // 获取的商品分类列表
      allgoods: [],
      // 级联选择框的配置对象
      goodsprops: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // 级联选择框双向数据绑定的数组
      value: [],
      // 动态参数获取的数据
      manyTabData: [],
      // 静态参数获取的数据
      onlyTabData: [],
      // 添加参数对话框默认隐藏
      addParamVisible: false,
      // 添加参数的表达数据对象
      addForm: {
        attr_name: ""
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur"
          }
        ]
      },
      // 控制修改对话框的显示与隐藏
      editParamVisible: false,
      // 修改的表单数据对象
      editForm: {},
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getcat_goods();
  },
  methods: {
    async getcat_goods() {
      const { data: res } = await this.$http.get("categories");
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败");
      }
      this.allgoods = res.data;
    },
    handleChange() {
      // console.log(this.value);
      this.getparamsData();
    },
    handleClick() {
      // console.log(this.activeName);

      this.getparamsData();
    },
    // 获取参数列表数据
    async getparamsData() {
      // 判断是否为三级标签状态
      if (this.value.length !== 3) {
        this.value = [];
        this.manyTabData = [];
        this.onlyTabData = [];
        return;
      }
      console.log(this.value);
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("获取参数列表失败");
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框输入的值
        item.inputValue = "";
      });
      console.log(res);

      if (this.activeName == "many") {
        this.manyTabData = res.data;
      } else {
        this.onlyTabData = res.data;
      }
    },
    addparams() {
      this.addParamVisible = true;
    },
    // 监听对话框关闭时间
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    confirmParam() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error("添加参数失败");
        const { data: res } = await this.$http.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败");
        }
        this.$message.success("添加参数成功");
        this.addParamVisible = false;
        this.getparamsData();
      });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async editParams(id) {
      // console.log(id);

      this.editParamVisible = true;
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("修改参数失败");
      }
      this.editForm = res.data;
      //  console.log(this.editForm);
    },
    confirmParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.catId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        );
        // console.log(res);
        this.editParamVisible = false;
        this.getparamsData();
      });
    },
    deleteParam(attr_id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.catId}/attributes/${attr_id}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          } else {
            this.$message.success("删除成功");
            this.getparamsData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果没有return，则有值，进行后续操作
      row.attr_vals.push(row.inputValue);
      row.inputVisible = false;
      this.saveTag(row);
      row.inputValue = "";
    },
    handleclose(row, i) {
      row.attr_vals.splice(i, 1);
      this.saveTag(row);
    },
    async saveTag(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.catId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("编辑参数失败");
      }
      this.$message.success("编辑参数成功");
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  },
  computed: {
    // 判断添加参数是否为选中状态
    isDisabled() {
      if (this.value.length == 3) {
        return false;
      } else {
        return true;
      }
    },
    // 当前选中的三级分类的Id
    catId() {
      if (this.value.length == 3) {
        return this.value[2];
      } else {
        return null;
      }
    },
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    }
  }
};
</script>
<style lang="less" scoped>
.cat_goods {
  display: inline-block;
  margin-top: 20px;
}
.selection {
  display: inline-block;
  margin-left: 10px;
}
.el-button {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>